package com.example.service.impl;

import com.example.algorithm.SnowflakeIdWorker;
import com.example.entity.Collection;
import com.example.entity.Topic;
import com.example.repository.CollectionRepository;
import com.example.repository.TopicRepository;
import com.example.service.TopicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class TopicServiceImpl implements TopicService {

    @Autowired
    private TopicRepository topicRepository;
    @Autowired
    private CollectionRepository collectionRepository;

    @Override
    public List<Topic> getTopics() {
        return topicRepository.findAll();
    }

    @Override
    public Topic getTopic(String topicId, String userId) {
        Topic topic = topicRepository.findById(topicId).get();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
        topic.setCreateAtFormat(simpleDateFormat.format(topic.getCreateAt()));
        topic.setUpdateAtFormat(simpleDateFormat.format(topic.getUpdateAt()));
        isCollection(topic, userId);
        return topic;
    }

    @Override
    public List<Topic> getTopicsByName(String topicName) {
        return topicRepository.findByNameLike("%" + topicName + "%");
    }

    @Override
    public void addTopic(String name) {
        Topic topic = new Topic();
        topic.setId(SnowflakeIdWorker.generateId() + "");
        topic.setName(name);
        topic.setCreateAt(new Date());
        topic.setCreateBy("admin");
        topic.setDel(false);
        topic.setUpdateAt(new Date());
        topic.setUpdateBy("admin");
        topicRepository.save(topic);
    }

    /**
     * 判断该主题是否被用户收藏，把信息完善到对象中
     * @param topic 主题对象
     * @return
     */
    public void isCollection(Topic topic, String userId){
        Collection collection = collectionRepository.findByUserIdAndTopicId(userId, topic.getId());
        if(collection!=null){
            topic.setCollection(true);
        }
    }
}
